package com.wswy.wzcx.ui.main.garage

import android.arch.lifecycle.Observer
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.wswy.wzcx.R
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.module.base.CBaseFragment

class GarageFragment : CBaseFragment() {

    private companion object {
        private const val TIPS = "add_tips"
        private const val CARS = "cars"
    }

    private lateinit var garageViewModel: GarageViewModel

    private var currentTag :String ? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val layout =  inflater.inflate(R.layout.fragment_nav_garage,container,false)
        //UiUtils.injectStatusBar(layout.findViewById(R.id.fl_container))
        return layout
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        garageViewModel = provideViewModelFromActivity(GarageViewModel::class.java)
        garageViewModel.onCreate()


        garageViewModel.getUserCarsLiveData().observe(this, Observer {

            it?.run {


                if (!inLoading()){

                    switchPage(data)

                }

            }
        })

        garageViewModel.getUserLiveData().observe(this, Observer {
            //
            garageViewModel.loadMyCars(false)
        })


        garageViewModel.carUpdateCallback = {

            if (TextUtils.equals(currentTag, TIPS)){
                garageViewModel.loadMyCars(false)
            }
        }

        garageViewModel.carDeleteCallback = {
            garageViewModel.loadMyCars(false)
        }

    }



    private fun switchPage(list: List<UserCarInfo>?){
        if (list?.isNotEmpty() == true){

            //已登录  有车

            if (currentTag != CARS){
                currentTag = CARS

                childFragmentManager.beginTransaction().replace(R.id.fl_container,CarsFragment(), currentTag).commitNow()
            }

        }else{
            //未登录 或者 没车

            if (currentTag != TIPS) {

                currentTag = TIPS

                childFragmentManager.beginTransaction().replace(R.id.fl_container, AddTipsFragment(), currentTag).commitNow()

            }
        }
    }

}